import java.util.Arrays;

public class LeetCode3298 {
    public long validSubstringCount(String word1, String word2) {
        long res = 0;
        int[] arr = new int[26];
        for (char c : word2.toCharArray()) {
            arr[c - 'a']--;
        }
        int[] cnt = {(int) Arrays.stream(arr).filter(c -> c < 0).count()};
        int l = 0, r = 0;
        while (l < word1.length()) {
            while (r < word1.length() && cnt[0] > 0) {
                update(arr, word1.charAt(r) - 'a', 1, cnt);
                r++;
            }
            if (cnt[0] == 0) {
                res += word1.length() - r + 1;
            }
            update(arr, word1.charAt(l) - 'a', -1, cnt);
            l++;
        }
        return res;
    }

    public void update(int[] arr, int c, int add, int[] cnt) {
        arr[c] += add;
        if (add == 1 && arr[c] == 0) {
            // 表明arr[c] 由-1 变为0
            cnt[0]--;
        } else if (add == -1 && arr[c] == -1) {
            // 表明 arr[c] 由 0 变为 -1
            cnt[0]++;
        }
    }

    public static void main(String[] args) {
        LeetCode3298 solution = new LeetCode3298();
        System.out.println(solution.validSubstringCount("abcde", "ace")); // Example usage
    }
}



